package com.lj.bruth.service;

import com.lj.bruth.controller.HelloController;
import com.lj.bruth.model.User;
import com.lj.bruth.dao.*;
import com.lj.bruth.model.UserDuXieFenLi;
import io.shardingsphere.api.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;

@Service
public class UserServiceImpl implements UserService{

    private static Logger logger = Logger.getLogger(HelloController.class.getName());

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserDuXieFenLiDao userDuXieFenLiDao;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public List<User> queryUser() {
        //List<User> all = userDao.findAll();
        //User byId = null;
        List<User> users = new ArrayList<>();
        try {
            users = userDao.findTongguoId();
        }catch (Exception e){
            //注意：分库分表完数据后查询是走所有涉及的表
            //logger.info("在不同表中存在相同数据,违背了分库分表原则，请排查问题，及时剔除不符合分库分表的数据!");
        }

        //users.add(byId);
        return users;
    }

    @Override
    public List<User> insertAndResisUser(List<User> list) {
        List <User> users = new ArrayList<>();
        try {
            for (User user : list) {
                User userNew = new User();
                if (user.getOrderId() != 0) {
                    //Optional<User> present= userDao.findById(user.getOrderId());
                    //if (!present.isPresent()) {
                        //jpa sava有数据为修改没数据就是新增，所以没必要判断
                        userNew = userDao.save(user);
                        users.add(userNew);
                    //}
                }
            }
        }catch (Exception e){
            logger.info("数据处理错误！！！"+e);
        }
        return users;
    }

    @Override
    public List<UserDuXieFenLi> insertUserByDuXieFenLi(List<UserDuXieFenLi> list) {
        List<UserDuXieFenLi> listNew = new ArrayList<UserDuXieFenLi>();
        for (UserDuXieFenLi u:list){
            UserDuXieFenLi userDuXieFenLi = userDuXieFenLiDao.save(u);
            listNew.add(userDuXieFenLi);
        }
        return listNew;
    }

    @Override
    public List<User> getHintData(Long dataBaseNum,Long tableBaseNum) {
        // Hint分片策略必须要使用 HintManager工具类
        HintManager hintManager = HintManager.getInstance();
        hintManager.addDatabaseShardingValue("t_order",dataBaseNum.intValue());
        hintManager.addTableShardingValue("t_order",tableBaseNum.intValue());
        // 直接指定对应具体的数据库
        //hintManager.setDatabaseShardingValue(1);
        //在读写分离数据库中，Hint 可以强制读主库（主从复制是存在一定延时，但在业务场景中，可能更需要保证数据的实时性）
        //hintManager.setMasterRouteOnly();
        return userDao.findAll();
    }


}
